#include "vtor_string_player.h"

#ifdef __VTOR_STRING_PLAYER__

//https://zhidao.baidu.com/question/1929397911420653787.html
static const short VtorStringPlayer_toneArray[] = { 0,
		262,  294,  330,  349,  392,  440,  494,
		523,  587,  659,  698,  784,  880,  988,
		1047, 1175, 1319, 1397, 1568, 1760, 1967
};

static const char VtorStringPlayer_symbolLengthTable[][2] = {
	'.', 1,
	',',10,
	':',40,
	';',60,
	'=',100,
	'\0',0
};

void VtorStringPlayer_SwitchMusic(VtorStringPlayer* player)
{
	//printf("pre %p %s\r\n", player->sentence, *player->sentence);
	player->music++;
	// 如果指向最后的曲子，将其回指向开头
	if(NULL == *player->music)
	{
		player->music = player->list;
	}
	player->charactor = *player->music;
	VtorStringPlayer_SwitchMusicCallback(player);
	//printf("end %p %s\r\n", player->sentence, *player->sentence);
}

void VtorStringPlayer_Run(VtorStringPlayer* player)
{
	// 当前音调，当前音调长度，当前频率
	if (player->toneLen <= 0)
	{
		// 将音调与音长清零，用局部变量在最后赋值即可
		signed char toneIdx = __VTOR_STRING_PLAYER_CONFIG_MIDDLE_OFFSET__;
		char toneLen = 0;
		char toneFlag = 0;
		while(1)
		{
			if('\0' == *(player->charactor))
			{
				// 到了句子结尾，唱下一句或切歌或从列表头开始
				VtorStringPlayer_SwitchMusic(player);
			}
			char curChar = *(player->charactor);

			// 如果已有音调，且此时为数字，
			// 得知音调“6”“+1”“++5”“-5”等，
			// 由“+-”或数字开头
			if('+' == curChar
				|| '-' == curChar
				|| ('0' <= curChar
					&& curChar <= '7'))
			{
				// 如果已经拿到过一个音调
				// 说明现在已经进入了下一个音调处理范畴，
				// 退出是最好选择
				if(toneFlag)
				{
					break;
				}
				if('-' == curChar)
				{
					toneIdx -= 10;
				}
				else if('+' == curChar)
				{
					toneIdx += 10;
				}
				// 0代表静音，1~7代表不同音调
				else if('0' <= curChar && curChar <= '7')
				{
					// 出现了数字，说明当前音调已经得到
					toneFlag  = 1;
					// 对于降调，由不同的处理方法
					if(toneIdx < 0)
					{
						toneIdx += __VTOR_STRING_PLAYER_CONFIG_MIDDLE_OFFSET__
							- (curChar - '0');
					}
					else
					{
						toneIdx += (curChar - '0');
					}
				}
			}

			// 开始计算音调长度
			int i;
			for(i = 0; VtorStringPlayer_symbolLengthTable[i][0] != '\0'; i++)
			{
				if(curChar == VtorStringPlayer_symbolLengthTable[i][0])
				{
					toneLen += VtorStringPlayer_symbolLengthTable[i][1];
					break;
				}
			
			}
			// while内每次循环只处理1个字符
			player->charactor++;
		}
		// 整个while循环只处理1个音调
		// 为缺省的音长修正为基本节拍长度
		if(0 == toneLen)
		{
			toneLen = player->presetToneLen;
		}
		if(__VTOR_STRING_PLAYER_CONFIG_MIDDLE_OFFSET__ == toneIdx)
		{
			toneIdx = 0; // 将偏置调整成0，静音
		}
		player->tone = toneIdx;
		player->toneLen = toneLen;
		// toneIdx不连续，将其紧凑
		if (0 <= toneIdx && toneIdx <= 27)
		{
			toneIdx =toneIdx / 10 * 7 + toneIdx % 10;
			// 输入27，输出高音7
			player->freq = VtorStringPlayer_toneArray[toneIdx];
			VtorStringPlayer_PlayFreq(player);
/*
			printf("%s[%s] -> tone %d -> toneIdx %d len %d freq %d\r\n",
				*player->sentence, player->charactor,
				player->tone, toneIdx, player->toneLen, player->freq);
*/
		}
	}
	player->toneLen--;
}

#endif // __VTOR_STRING_PLAYER__

